<template>
  <div class="de-detail">
    <div class="qup-title-box"><span class="border" /><span>走访基本信息</span></div>
    <div v-loading="baseInfoLoading">
      <c-list
        ref="form"
        label-width="130px"
        :column="3"
      >
        <el-form-item label="门店编码:" prop="shopCode">
          <input-with-dialog
            v-model="shop"
            :disabled="!!patrolId"
            :props="{label:'code',value:'code'}"
            :config="dialogConfigShop"
            @change="handleChangeShop"
          />
        </el-form-item>
        <c-list-item :span="2" type="text" label="门店名称" :value="shopDetail.shopName" />
        <c-list-item :span="2" type="text" label="门店地址" :value="shopDetail.shopAddress" />
        <c-list-item dict-type-code="SHOP_BIZ_STATE" type="text" label="账号状态" :value="shopDetail.shopBizState" />
        <c-list-item type="text" label="门店业务类型" :value="shopDetail.businessTypeName" />
        <c-list-item type="text" label="市场层级" :value="shopDetail.marketLevelName" />
        <c-list-item type="text" label="门店面积(㎡)" :value="shopDetail.operateArea" />
        <c-list-item type="text" label="客户编码" :value="shopDetail.customerCode" />
        <c-list-item type="text" label="客户名称" :span="2" :value="shopDetail.customerName" />
        <c-list-item type="text" label="经销商姓名" :value="shopDetail.customerLinkMan" />
        <c-list-item type="text" label="办事处" :value="shopDetail.officeName" />
        <c-list-item type="text" label="办事处客服主管" :value="shopDetail.officeLinkMan" />
        <c-list-item type="text" label="办事处客服主管电话" :value="shopDetail.officeLinkPhone" />
        <c-list-item type="text" label="成品客户经理" :value="shopDetail.finishedManagerName" />
        <c-list-item type="text" label="成品客户经理电话" :value="shopDetail.finishedManagerPhone" />
        <c-list-item type="text" label="定制客户经理" :value="shopDetail.customManagerName" />
        <c-list-item type="text" label="定制客户经理电话" :value="shopDetail.customManagerPhone" />
      </c-list>
    </div>
    <div class="qup-title-box"><span class="border" /><span>走访申请信息</span></div>
    <div v-loading="patrolInfoLoading">
      <c-list
        ref="form"
        label-width="130px"
        :column="3"
      >
        <c-list-item :span="3" type="text" label="走访任务号" :value="formData.patrolTaskNo" />
        <c-list-item dict-type-code="DAILY_STATUS" type="text" label="走访任务进度" :value="formData.schedule" />
        <el-form-item label="走访人员:" prop="personCode">
          <input-with-dialog
            v-model="person"
            :disabled="isDetail"
            :props="{label:'userName',value:'account'}"
            multiple
            :config="{
              title:'走访人员',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/user/domainMarketingUser/page',
              method:'post',
              filtersRaw: [{ 'id': 'state', 'property': 'state', 'value': 1, 'operator': '=' }],
              paramsRaw:{},
              setting:[
                {prop:'account',title:'编码'},
                {prop:'userName',title:'名称'},
                {prop:'orgName',title:'组织'},
              ]
            }"
            @change="handleChangePerson"
          />
        </el-form-item>
        <c-list-item type="date" label="走访开始时间" :value="formData.beginTime">
          <el-date-picker
            v-model="formData.beginTime"
            :disabled="isDetail"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item type="date" label="走访结束时间" :value="formData.endTime">
          <el-date-picker
            v-model="formData.endTime"
            :disabled="isDetail"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            clearable
          />
        </c-list-item>
        <c-list-item type="date" label="门店实际状态" :value="formData.shopStatus">
          <c-dict-select v-model="formData.shopStatus" :disabled="isDetail" dict-type-code="ACTUAL_STATE" placeholder="门店实际状态" />
        </c-list-item>
        <c-list-item :disabled="isDetail" type="text" label="总体评价" :value="countLevel(formData.score)" />
        <c-list-item type="date" label="总体分数">
          <el-input-number v-model="formData.score" :min="0" :max="100" :disabled="isDetail" size="mini" />
        </c-list-item>
        <c-list-item type="text" label="走访申请人" :value="formData.createBy" />
        <c-list-item type="text" label="走访申请时间" :value="formData.createTime" />
      </c-list>
    </div>
    <div class="qup-title-box"><span class="border" /><span>门店变更信息</span></div>
    <div v-if="!isDetail" style="padding-bottom:10px">
      <el-button size="mini" type="primary" @click.native="handleAdd">新增</el-button>
      <el-button size="mini" type="primary" @click.native="handleEdit">编辑</el-button>
      <el-button size="mini" type="primary" @click.native="handleSave">保存</el-button>
      <el-button v-show="patrolId" size="mini" type="primary" @click.native="handelQueryShopChange()">取消</el-button>
    </div>
    <el-table
      :data="tableData"
      border
      max-height="300"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column width="120" prop="fieldCode" label="变更字段">
        <template slot-scope="scope">
          {{ formaterData(fieldCodeOptions,scope.row.fieldCode) }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="beforeValue" label="变更前值">
        <template slot-scope="scope">
          <span v-if="scope.row.fieldCode==='A'">{{ formaterData(shopbizOptions,scope.row.beforeValue) }} </span>
          <span v-else>{{ scope.row.beforeValue }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="afterValue" label="变更后值">
        <template slot-scope="scope">
          <span v-if="scope.row.fieldCode==='A'">{{ formaterData(shopbizOptions,scope.row.afterValue) }} </span>
          <span v-else>{{ scope.row.afterValue }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="qup-title-box"><span class="border" /><span>走访参与人合作信息</span></div>
    <c-list
      ref="form"
      :model="joinerData"
      :rules="formRules"
      label-width="130px"
      :column="3"
      style="margin-bottom:40px"
    >

      <c-list-item type="text" label="参与人合照/现场照片">
        <div class="img-upload-container">
          <import-img
            :photo-list="fileList"
            :readonly="isDetail"
            :limited="20"
            :config-attachment-id="picConfigId"
          />
        </div>
      </c-list-item>
      <c-list-item :span="2" type="text" label="拍摄地址" :value="joinerData.address">
        <el-input v-model="joinerData.address" :disabled="isDetail" />
      </c-list-item>
      <c-list-item type="text" label="经度" :value="joinerData.longitude">
        <el-input v-model="joinerData.longitude" :disabled="isDetail" />
      </c-list-item>
      <c-list-item type="text" label="纬度" :value="joinerData.latitude">
        <el-input v-model="joinerData.latitude" :disabled="isDetail" />
      </c-list-item>
    </c-list>
    <el-dialog
      v-if="showDlg"
      ref="refDlg"
      :visible.sync="showDlg"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialog"
      width="400px"
      :title="editForm.id?'编辑':'新增'"
      @close="closeDialog"
    >
      <el-form ref="refForm" :rules="editRules" :model="editForm" size="mini" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="变更字段:" prop="fieldCode">
              <el-select
                v-model="editForm.fieldCode"
                placeholder="请选择"
                :disabled="!!editForm.id||!editForm.isEdit"
                @change="changeFieldCode"
              >
                <el-option
                  v-for="item in fieldCodeOptions"
                  :key="item.dictCode"
                  :disabled="filterChangeSelect(item.dictCode)"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="变更前值:" prop="beforeValue">
              <c-dict-select
                v-if="editForm.fieldCode==='A'"
                v-model="editForm.beforeValue"
                disabled
                dict-type-code="SHOP_BIZ_STATE"
              />
              <el-input v-else v-model="editForm.beforeValue" disabled size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="变更后值:">
              <span v-if="editForm.fieldCode==='A'">
                <c-dict-select
                  v-model="editForm.afterValue"
                  :disabled="!editForm.fieldCode"
                  dict-type-code="SHOP_BIZ_STATE"
                />
              </span>
              <span v-else-if="editForm.fieldCode==='B'">
                <c-dict-select
                  v-model="editForm.afterValue"
                  multiple
                  :disabled="!editForm.fieldCode"
                  label-value="dictName"
                  dict-type-code="BIZ_TYPE"
                />
              </span>
              <span v-else-if="editForm.fieldCode==='C'">
                <c-dict-select
                  v-model="editForm.afterValue"
                  :disabled="!editForm.fieldCode"
                  label-value="dictName"
                  dict-type-code="MARKET_LEVEL"
                />
              </span>
              <span v-else>
                <el-input v-model="editForm.afterValue" :disabled="!editForm.fieldCode" size="mini" />
              </span>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button :loading="saveLoading" size="mini" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getShopDetailByCode, queryFormDetailById, saveShopChange, queryShopChangeList } from '@/api/marketService/dailyPatrol'
import { filterURL, formaterData } from '@/utils'
import { getShopAttachment } from '@/api/common'
import importImg from '@/components/importImg/miniUpload'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'BaseInfo',
  components: { importImg },
  props: {
    shopCode: {
      type: String,
      default: ''
    },
    patrolId: {
      type: String,
      default: ''
    },
    picConfigId: {
      type: String,
      default: ''
    },
    isDetail: {
      type: [Number, Boolean],
      default: false
    }
  },
  data() {
    return {
      formaterData,
      editForm: {},
      showDlg: false,
      saveLoading: false,
      fileList: [],
      fieldCodeOptions: [],
      shopbizOptions: [],
      filterURL,
      baseInfoLoading: false,
      patrolInfoLoading: false,
      showPicDetail: false,
      tableData: [],
      formData: {
        address: '',
        beginTime: '',
        endTime: '',
        id: '',
        latitude: '',
        longitude: '',
        personCode: '',
        personName: '',
        score: 0,
        shopAttachmentDTOList: [],
        shopChangeIds: [],
        shopCode: '',
        shopStatus: '',
        patrolTaskNo: ''
      },
      joinerData: { address: '', longitude: '', latitude: '' }, // 走访参与人合作信息
      shopDetail: {}, // 门店信息
      formRules: {},
      shop: [],
      person: [],
      oldPics: [],
      tableSelected: [],
      dialogConfigShop: {
        title: '门店',
        filtersRaw: [{ 'id': 'status', 'property': 'status', 'value': '1', 'operator': '=' }],
        pageFlag: false,
        interfacePath: `/select-service/api/v1/shop/page`,
        setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }]
      },
      editRules: {
        afterValue: [{ required: true, message: '请选择', trigger: 'change' }],
        fieldCode: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  computed: {
    tableDataValue() {
      return this.tableData.map(v => v.fieldCode)
    }
  },
  watch: {
    shopCode: {
      handler(v) {
        if (!v) return
        this.handelQueryShopData(v)
      },
      deep: true,
      immediate: true
    },
    patrolId: {
      handler(v) {
        if (!v) return
        this.handelQueryDetail(v)
        this.handelQueryShopChange(v)
      },
      deep: true,
      immediate: true
    }
  },
  async created() {
    const { CHANGE_SHOP_FIELD, SHOP_BIZ_STATE } = await getDictByPatchType(['CHANGE_SHOP_FIELD', 'SHOP_BIZ_STATE'])
    this.fieldCodeOptions = CHANGE_SHOP_FIELD
    this.shopbizOptions = SHOP_BIZ_STATE
  },
  methods: {
    closeDialog() {
      this.showDlg = false
      this.saveLoading = false
      this.editForm = {}
    },
    filterChangeSelect(dictCode) {
      return this.tableDataValue.includes(dictCode)
    },

    changeFieldCode(v) {
      // A-账号状态
      // B-业务类型
      // C-市场层级
      // D-门店面积
      // E-门店地址
      switch (v) {
        case 'A':
          // SHOP_BIZ_STATE
          this.editForm.beforeValue = this.shopDetail.shopBizState
          this.editForm.afterValue = this.shopDetail.shopBizState
          break
        case 'B':
          this.editForm.beforeValue = this.shopDetail.businessTypeName
          this.editForm.afterValue = this.shopDetail.businessTypeName
          break
        case 'C':
          this.editForm.beforeValue = this.shopDetail.marketLevelName
          this.editForm.afterValue = this.shopDetail.marketLevelName
          break
        case 'D':
          this.editForm.beforeValue = this.shopDetail.operateArea
          this.editForm.afterValue = this.shopDetail.operateArea
          break
        case 'E':
          this.editForm.beforeValue = this.shopDetail.shopAddress
          this.editForm.afterValue = this.shopDetail.shopAddress
          break
        default:
          this.editForm.beforeValue = ''
          this.editForm.afterValue = ''
          break
      }
    },
    async getData() {
      const data = { ...this.formData,
        ...this.joinerData,
        operateArea: this.shopDetail.operateArea,
        shopAttachmentDTOList: this.fileList.map(v => { return { ...v, attachmentType: '参与人合照' } }),
        shopChangeIds: this.tableData.map(i => i.id)
        // shopAttachmentDTOList: this.pic && this.pic.attachmentUrl ? [{
        //   ...this.pic,
        //   configAttachmentId: this.picConfigId,
        //   attachmentType: '参与人合照',
        //   modelId: this.patrolId
        // }] : []
      }
      return data
    },
    countLevel(score) {
      if (!score) return ''
      const data = Number(score || 0)
      if (data >= 90) return '好'
      else if (data >= 80) return '较好'
      else if (data >= 60) return '较差'
      else if (data < 60) return '差'
    },
    handleAdd() {
      if (!this.shopDetail.shopCode) {
        this.$message.warning('请先选择门店')
        return
      }
      const item = {
        addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
        afterValue: '',
        beforeValue: '',
        fieldCode: '',
        fieldName: '',
        id: null,
        patrolId: this.patrolId,
        isEdit: true,
        shopCode: this.shopCode || this.formData.shopCode
      }
      this.editForm = item
      this.showDlg = true
      // this.tableData.push(item)
    },
    handleEdit() {
      if (!this.singleJudge(this.tableSelected, '编辑', true)) {
        return
      }
      this.editForm = this.tableSelected[0]
      this.showDlg = true
      // const KeyIndex = this.tableData.findIndex(v => (v.id && this.tableSelected[0].id && v.id === this.tableSelected[0].id) || (v.addFlag && this.tableSelected[0].addFla && v.addFlag === this.tableSelected[0].addFlag))
      // this.$set(this.tableData[KeyIndex], 'isEdit', true)
    },
    handelQueryShopChange(id) {
      const queryId = id || this.patrolId
      if (!queryId || !this.shopCode) {
        this.tableData = []
        return
      }
      queryShopChangeList(queryId, this.shopCode).then(res => {
        if (res.success) {
          this.tableData = res.data.records
        }
      })
    },
    handelQueryDetail(id) {
      this.patrolInfoLoading = true
      queryFormDetailById(id).then(res => {
        if (res.success) {
          const { schedule, patrolTaskNo, beginTime, endTime, id, personCode, personName, score, shopCode, shopStatus } = res.data
          this.formData = { schedule, patrolTaskNo, beginTime, endTime, id, personCode, personName, score, shopCode, shopStatus }
          this.person = [{ label: personName, value: personCode }]
          const { address, longitude, latitude } = res.data// 走访参与人合作信息
          this.joinerData = { address, longitude, latitude }
        }
        this.patrolInfoLoading = false
      }).catch(() => {
        this.patrolInfoLoading = false
      })
      getShopAttachment(id).then(res => {
        if (res.success && res.data) {
          this.fileList = res.data.filter(v => v.attachmentType === '参与人合照')
        }
      })
    },
    handleChangePerson(data) {
      if (data.length !== 0) {
        this.$set(this.formData, 'personCode', data.map(i => i.account).join(','))
        this.$set(this.formData, 'personName', data.map(i => i.userName).join(','))
      } else {
        this.$set(this.formData, 'personCode', '')
        this.$set(this.formData, 'personName', '')
      }
    },
    async   handleSave() {
      // if (!this.singleJudge(this.tableSelected, '保存', true)) {
      //   return
      // }
      if (this.editForm.beforeValue === this.editForm.afterValue) {
        this.$message.warning('变更前后值不能相同')
        return
      }
      let submitData = { ...this.editForm, shopCode: this.shopCode || this.formData.shopCode }
      if (this.editForm.fieldCode === 'B') submitData = { ...this.editForm, afterValue: this.editForm.afterValue.join(',') }
      this.saveLoading = true
      const resId = await saveShopChange(submitData)
      this.saveLoading = false
      // const keyIndex = this.tableData.findIndex(i => (i.id && this.editForm.id && i.id === this.editForm.id) || (i.addFlag && this.editForm.addFlag && i.addFlag === this.editForm.addFlag))
      this.$message.success('保存成功')
      if (this.patrolId) this.handelQueryShopChange()
      else {
        // 新增基础数据
        const keyIndex = this.tableData.findIndex(i => i.addFlag && this.editForm.addFlag && i.addFlag === this.editForm.addFlag)
        if (keyIndex !== -1) { // 表格中有此数据
          this.tableData[keyIndex] = this.editForm
        } else {
          this.$set(this.editForm, 'id', resId)
          this.tableData.push(this.editForm)
        }
      }
      this.closeDialog()
    },
    handleSelectionChange(rows) {
      this.tableSelected = rows
    },
    handleChangeShop(data) {
      if (data.length !== 0) {
        this.handelQueryShopData(data[0].code)
      } else {
        this.shopDetail = {}
      }
    },
    handelQueryShopData(shopCode) {
      this.baseInfoLoading = true
      getShopDetailByCode(shopCode).then(res => {
        if (res.success) {
          const { shopName, shopCode, shopAddress, shopBizState, businessTypeName, marketLevelName, operateArea,
            customerLinkMan, officeLinkMan, officeLinkPhone, finishedManagerName, finishedManagerPhone, customManagerName,
            customManagerPhone, officeCode, officeName, customerCode, customerName } = res.data
          this.shopDetail = { shopName, shopCode, shopAddress, shopBizState, businessTypeName, marketLevelName, operateArea,
            customerLinkMan, officeLinkMan, officeLinkPhone, finishedManagerName, finishedManagerPhone, customManagerName,
            customManagerPhone, officeCode, officeName, customerCode, customerName }
          this.$set(this.formData, 'shopCode', shopCode)
          this.shop = [{ label: shopCode, value: shopCode }]
        }
        this.baseInfoLoading = false
      }).catch(() => {
        this.baseInfoLoading = false
      })
    },
    clearForm(done) {
      this.shopDetail = {}
      this.joinerData = { address: '', longitude: '', latitude: '' }
      this.formData = {
        address: '',
        beginTime: '',
        endTime: '',
        id: '',
        latitude: '',
        longitude: '',
        personCode: '',
        personName: '',
        score: 0,
        shopAttachmentDTOList: [],
        shopChangeIds: [],
        shopCode: '',
        shopStatus: ''
      }
      this.$refs.rulesForm && this.$refs.rulesForm.clearValidate()
      done && done()
    }
  }
}
</script>
<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/.el-breadcrumb__inner{
  color: $qup-color-primary;
}
.el-table td div{
  width: 100%;
}
</style>
